<template>
  <div class="address">
    <van-nav-bar
      :title="aid ? '编辑地址' : '新增地址'"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <Bg>
      <van-address-edit
        :area-list="directory"
        show-postal
        :show-delete="aid"
        show-set-default
        show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="save"
        @delete="onDelete"
        :address-info="addressInfo"
      />
    </Bg>
  </div>
</template>

<script>
import Bg from "../components/Bg.vue";
import "../assets/less/address.less";
import directory from "../assets/js/area.js";
export default {
  name: "Address",
  components: {
    Bg,
  },
  data() {
    return {
      // 地区选择
      directory,

      //路由参数
      aid: "",

      //地址初始化信息
      addressInfo: {},
    };
  },
  created() {
    //截取路由参数
    this.aid = this.$route.params.aid;

    // 编辑地址
    if (this.aid) {
      this.getAddressData();
    }
  },
  methods: {
    //新增地址
    add(value) {
      let tokenString = this.$cookies.get("tokenString");
      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      let appkey = this.appkey;
      let data = { ...value, tokenString, appkey };
      delete data.country;
      data.isDefault = Number(data.isDefault);

      console.log(data);

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/addAddress",
        data: data,
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          } else if (result.data.code === 9000) {
            this.$router.push({ name: "AddressList" });
          }
          this.$toast({
            message: result.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 编辑地址
    edi(value) {
      console.log("edi==>", value);
      let isEdi = false;

      for (let key in this.addressInfo) {
        if (this.addressInfo[key] !== value[key]) {
          isEdi = true;
          break;
        }
      }

      if (isEdi) {
        // 发送编辑请求
        let tokenString = this.$cookies.get("tokenString");
        //当用户未登录的时候跳转到登录页面
        if (!tokenString) {
          return this.$router.push({ name: "Login" });
        }

        let appkey = this.appkey;
        let data = {};
        data.appkey = appkey;
        data.tokenString = tokenString;
        data.aid = value.aid;
        data.name = value.name;
        data.tel = value.tel;
        data.province = value.province;
        data.city = value.city;
        data.county = value.county;
        data.addressDetail = value.addressDetail;
        data.areaCode = value.areaCode;
        data.postalCode = value.postalCode;
        data.isDefault = Number(value.isDefault);

        console.log(data);

        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });

        this.axios({
          method: "post",
          url: this.baseUrl + "/editAddress",
          data: data,
        })
          .then((result) => {
            console.log(result);
            this.$toast.clear();
            if (result.data.code === 700) {
              this.$toast({
                message: result.data.msg,
                forbidClick: true,
                duration: 3000,
              });
              return this.$router.push({ name: "Login" });
            } else if (result.data.code === 30000) {
              this.$router.push({ name: "AddressList" });
            }
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          })
          .catch((err) => {
            this.$toast.clear();
            console.log(err);
          });
      }
    },

    // 添加或编辑
    save(value) {
      // console.log(value)
      if (value.aid) {
        // 编辑
        console.log("编辑");
        this.edi(value);
      } else {
        console.log("添加");
        this.add(value);
      }
    },

    // 根据aid获取地址数据
    getAddressData() {
      //查询地址数据
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "get",
        url: this.baseUrl + "/findAddressByAid",
        params: {
          appkey: this.appkey,
          tokenString,
          aid: this.aid,
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();

          if (result.data.code == 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (result.data.code === 40000) {
            let data = result.data.result[0];
            data.isDefault = !!data.isDefault;

            this.addressInfo = data;
            // console.log(this.addressInfo);
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },

    // 删除地址
    onDelete() {
      if (!this.aid) {
        return;
      }
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/deleteAddress",
        data: {
          appkey: this.appkey,
          tokenString: tokenString,
          aid: this.aid,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          } else if (result.data.code === 10000) {
            this.$router.push({ name: "AddressList" });
          }
          this.$toast({
            message: result.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 返回上一级
    onClickLeft() {
      this.$router.back();
    },
  },
};
</script>

<style lang="less" scoped>
</style>